package com.gears_software.sxdc.dccx.ui.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.GravityEnum;
import com.afollestad.materialdialogs.MaterialDialog;
import com.facebook.drawee.view.SimpleDraweeView;
import com.gears_software.sxdc.dccx.R;
import com.gears_software.sxdc.dccx.application.DCCXApplication;
import com.gears_software.sxdc.dccx.data.finder.IBaseFinder;
import com.gears_software.sxdc.dccx.data.finder.IZPOrderFinder;
import com.gears_software.sxdc.dccx.data.finder.RequestUrl;
import com.gears_software.sxdc.dccx.data.finder.util.GearsErrorHandler;
import com.gears_software.sxdc.dccx.data.model.AboutModel;
import com.gears_software.sxdc.dccx.data.model.MyTripZCDetailModel;
import com.gears_software.sxdc.dccx.data.model.ResultModel;
import com.gears_software.sxdc.dccx.data.model.request.RZCOrderRatedModel;
import com.gears_software.sxdc.dccx.ui.util.MaterialDialogProgress;
import com.sdsmdg.tastytoast.TastyToast;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.App;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.rest.spring.annotations.RestService;

import java.util.List;

import qiu.niorgai.StatusBarCompat;

/**
 * Created by chezhenzhen on 2017/9/19.
 */

@EActivity(R.layout.activity_mytrip_zc_detail)
public class MyTripZCListDetailActivity extends AppCompatActivity {
    @App
    DCCXApplication app;
    @ViewById
    TextView actionbar_title;
    @ViewById
    TextView back_icon;
    @ViewById
    TextView right_icon;
    @ViewById
    SimpleDraweeView img_avatar;
    @ViewById
    TextView txt_username;
    @ViewById
    TextView txt_vehicleno;
    @ViewById
    TextView txt_car;
    @ViewById
    TextView txt_vehiclecolor;
    @ViewById
    TextView txt_tel;
    @ViewById
    TextView txt_mx_right_icon;
    @ViewById
    TextView txt_payprice;
    @ViewById
    TextView txt_pay;
    @ViewById
    LinearLayout ly_mx;
    @ViewById
    LinearLayout ly_driver_pj;
    @ViewById
    LinearLayout ly_meto_pj;
    @ViewById
    RelativeLayout re_tousu;
    @ViewById
    RelativeLayout re_pay;
    @ViewById
    RelativeLayout re_hotline;
    @ViewById
    RelativeLayout re_submit;
    @ViewById
    RelativeLayout re_driver_ratingbar;
    @ViewById
    RatingBar ratingBar;
    @ViewById
    RatingBar ratingBar_to;
    @ViewById
    View line1;
    @ViewById
    View line2;
    @Extra
    String id;
    @RestService
    IZPOrderFinder izpOrderFinder;
    @RestService
    IBaseFinder baseFinder;
    @Bean
    GearsErrorHandler errorHandler;
    String type = "2"; //专车-乘客端
    MyTripZCDetailModel zcDetailModel;
    AboutModel aboutModel;
    MaterialDialogProgress progress;
    Context context;
    String phoneNumber;

    @AfterViews
    void created() {
        StatusBarCompat.setStatusBarColor(this, ContextCompat.getColor(this, R.color.colorActionbar));

        context = this;
        izpOrderFinder.setRestErrorHandler(errorHandler);
        baseFinder.setRestErrorHandler(errorHandler);
        initIconFont();
        progress = new MaterialDialogProgress(this);
        progress.show("正在加载...");
        getDetail();
    }

    void initIconFont() {
        actionbar_title.setText("行程详情");
        back_icon.setVisibility(View.VISIBLE);
        back_icon.setText(R.string.back_icon);
        back_icon.setTypeface(app.iconfont);
        right_icon.setVisibility(View.GONE);
        txt_tel.setTypeface(app.iconfont);
        txt_mx_right_icon.setTypeface(app.iconfont);
    }

    @Background
    void getDetail() {
        ResultModel<MyTripZCDetailModel> res = izpOrderFinder.getZCTripDetail(type, id);
        showDetailResult(res);
    }

    @UiThread
    void showDetailResult(ResultModel<MyTripZCDetailModel> res) {
        if (res != null) {
            if (res.getErrno().equals("0")) {
                if (res.getData() != null) {
                    zcDetailModel = res.getData();
                    if (zcDetailModel.getAvatar() != null && !zcDetailModel.getAvatar().equals("")) {
                        Uri uri = Uri.parse(zcDetailModel.getAvatar() + RequestUrl.avatar);
                        img_avatar.setImageURI(uri);
                    }
                    txt_username.setText(zcDetailModel.getDrivername());
                    txt_vehicleno.setText(zcDetailModel.getVehicleno());
                    txt_vehiclecolor.setText(zcDetailModel.getVehiclecolor());
                    txt_car.setText(zcDetailModel.getCarmodel());
                    txt_payprice.setText(zcDetailModel.getFactprice().subtract(zcDetailModel.getDiscountamount()).toString());
                    if (zcDetailModel.getOrderstatus() != null && zcDetailModel.getOrderstatus().equals("7")) {
                        ly_meto_pj.setVisibility(View.VISIBLE);
                        ratingBar_to.setVisibility(View.VISIBLE);
                        re_pay.setEnabled(false);
                        txt_pay.setText("已支付");
                        if (zcDetailModel.getPassengereva() != null && !zcDetailModel.getPassengereva().equals("")) {
                            if (zcDetailModel.getPassengereva().equals("0")) {
                                re_submit.setVisibility(View.VISIBLE);
                                ratingBar_to.setIsIndicator(false);
                                ratingBar_to.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
                                    @Override
                                    public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
                                        ratingBar_to.setRating(rating);
                                    }
                                });
                            } else if (zcDetailModel.getPassengereva().equals("1")) {
                                re_submit.setVisibility(View.GONE);
                                ratingBar_to.setIsIndicator(true);
                                if (zcDetailModel.getDriverrated() != 0) {
                                    ratingBar_to.setRating(zcDetailModel.getDriverrated());
                                }
                            }
                        }
                    } else {
                        re_pay.setEnabled(true);
                        ly_meto_pj.setVisibility(View.GONE);
                        ratingBar_to.setVisibility(View.GONE);

                    }

                    if (zcDetailModel.getDrivereva() != null && !zcDetailModel.getDrivereva().equals("")) {
                        if (zcDetailModel.getDrivereva().equals("0")) {
                            ly_driver_pj.setVisibility(View.GONE);
                            re_driver_ratingbar.setVisibility(View.GONE);
                        } else if (zcDetailModel.getDrivereva().equals("1")) {
                            if (zcDetailModel.getPassengerrated() != 0) {
                                ly_driver_pj.setVisibility(View.VISIBLE);
                                re_driver_ratingbar.setVisibility(View.VISIBLE);
                                ratingBar.setIsIndicator(true);
                                ratingBar.setRating(zcDetailModel.getPassengerrated());
                            }
                        }
                    }
                }
            }
        }
        progress.dismiss();
    }

    //拔打司机电话
    @Click
    void txt_tel() {
        phoneNumber = zcDetailModel.getDriverphone();
        showPhoneDialog(zcDetailModel.getDriverphone());
    }

    void showPhoneDialog(String phone) {
        new MaterialDialog.Builder(this)
                .title("提示")
                .titleGravity(GravityEnum.CENTER)
                .titleColorRes(R.color.colorFontBigGray)
                .content("您确定要拨打" + " " + phone)
                .contentColorRes(R.color.colorFontBigGray)
                .positiveText("确定")
                .positiveColor(ContextCompat.getColor(context, R.color.colorFontBlue))
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        AndPermission.with(context)
                                .requestCode(100)
                                .permission(Manifest.permission.CALL_PHONE)
                                .callback(listener)
                                .rationale(new RationaleListener() {
                                    @Override
                                    public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                                        // 这里的对话框可以自定义，只要调用rationale.resume()就可以继续申请。
                                        AndPermission.rationaleDialog(context, rationale).
                                                show();
                                    }
                                })
                                .start();
                    }
                })
                .negativeText("取消")
                .negativeColor(ContextCompat.getColor(context, R.color.colorFontGray))
                .onNegative(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        dialog.dismiss();
                    }
                })
                .buttonsGravity(GravityEnum.CENTER)
                .show();
    }

    private PermissionListener listener = new PermissionListener() {
        @Override
        public void onSucceed(int requestCode, List<String> grantedPermissions) {
            // 权限申请成功回调。
            if (requestCode == 100) {
                //打电话
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_CALL);
                intent.setData(Uri.parse("tel:" + phoneNumber));
                context.startActivity(intent);
            }
        }

        @Override
        public void onFailed(int requestCode, List<String> deniedPermissions) {
            // 权限申请失败回调。
            if (requestCode == 100) {
                TastyToast.makeText(context, "获取电话权限失败", TastyToast.LENGTH_SHORT, TastyToast.ERROR);
            }
        }
    };

    //联系客服
    @Click
    void re_hotline() {
        getAbout();
    }

    @Background
    void getAbout() {
        ResultModel<AboutModel> res = baseFinder.getAbout();
        showAboutResult(res);
    }

    @UiThread
    void showAboutResult(ResultModel<AboutModel> res) {
        if (res != null) {
            if (res.getErrno().equals("0")) {
                if (res.getData() != null) {
                    aboutModel = res.getData();
                    phoneNumber = aboutModel.getFtel();
                    showPhoneDialog(aboutModel.getFtel());
                }
            }
        }
    }

    //支付
    @Click
    void re_pay() {
        if (zcDetailModel.getOrderstatus().equals("6")) {
            Intent intent = new Intent(this, PayActivity_.class);
            intent.putExtra("type", "3");
            intent.putExtra("orderid", zcDetailModel.getId());
            intent.putExtra("orderNo", zcDetailModel.getOrderid());
            intent.putExtra("driverid", zcDetailModel.getDriverid());
            intent.putExtra("tradingType", "1");
            intent.putExtra("voucherid", zcDetailModel.getVoucherid());
            intent.putExtra("price", zcDetailModel.getFactprice());
            intent.putExtra("discountamount",zcDetailModel.getDiscountamount());
            startActivityForResult(intent, 5);
        } else {
            TastyToast.makeText(this, "不能进行支付", app.SHORT, app.WARNING);
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 5) {
            if (data != null) {
                int code = (int) data.getExtras().get("resultCode");
                if (code == 1) {
                    re_pay.setEnabled(false);
                    txt_pay.setText("已支付");
                    getDetail();
                }
            }
        }
    }

    //评价提交
    @Click
    void btn_submit() {
        RZCOrderRatedModel zcOrderRatedModel = new RZCOrderRatedModel();
        zcOrderRatedModel.setId(id);
        zcOrderRatedModel.setFlag("2");
        float rb = ratingBar_to.getRating();
        int rate = (int) rb;
        zcOrderRatedModel.setRate(String.valueOf(rate));
        goRated(zcOrderRatedModel);
    }

    @Background
    void goRated(RZCOrderRatedModel zcOrderRatedModel) {
        ResultModel<String> resultModel = izpOrderFinder.goZCOrderRate(zcOrderRatedModel);
        showRateResult(resultModel);
    }

    @UiThread
    void showRateResult(ResultModel<String> res) {
        if (res != null) {
            if (res.getErrno().equals("0")) {
                getDetail();
                TastyToast.makeText(this, "评价信息提交成功", app.SHORT, app.SUCCESS);
            } else {
                TastyToast.makeText(this, res.getErrmsg(), app.SHORT, app.ERROR);

            }
        }
    }

    //投诉
    @Click
    void re_tousu() {
        Intent intent = new Intent(this, ZCComplainActivity_.class);
        intent.putExtra("zcDetailModel", zcDetailModel);
        startActivity(intent);
    }

    //查看明细
    @Click
    void ly_mx() {
        Intent intent = new Intent(this, ChargeScheduleActivity_.class);
        intent.putExtra("id", zcDetailModel.getId());
        startActivity(intent);
    }

    @Click
    void back_icon(){
        this.finish();
    }

}
